package cn.btks.backstagemanage.role.controller;

import cn.btks.backstagemanage.menu.dto.MenuDto;
import cn.btks.backstagemanage.menu.pojo.MenuRolesDto;
import cn.btks.backstagemanage.menu.service.MenuService;
import cn.btks.backstagemanage.role.dto.RoleDto;
import cn.btks.backstagemanage.role.pojo.Role;
import cn.btks.backstagemanage.role.service.RoleService;
import cn.btks.backstagemanage.unit.pojo.Unit;
import cn.btks.commonserver.result.MenuSourceEnum;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.result.SystemLogEnum;
import cn.btks.commonserver.util.JwtUtil;
import cn.btks.commonserver.valid.SystemLog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author lijun
 * @Date 2021/1/13 11:18
 */
@RestController
@RequestMapping("api/v1.0/role")
@Api(tags = "角色模块")
@Validated
public class RoleController {

    @Autowired
    RoleService roleService;

    @Autowired
    MenuService menuService;

    @SystemLog(type = SystemLogEnum.QUERY_LOG,moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @GetMapping("/findAll")
    @ApiOperation("查询所有角色")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "token密匙", required = true, dataType = "string")
    })
    public ResultState findAll(HttpServletRequest request) throws Exception {
        List<Role> roleList = new ArrayList<>();
        String token = request.getHeader("token");
        Optional<Claims> optional = JwtUtil.getClaimsFromToken(token, JwtUtil.jwtsSecret);
        if(optional.isPresent()) {
            Claims claims = optional.get();
            Object obj = claims.get("unit");
            Unit unit = JSONArray.parseObject(JSON.toJSONString(obj), Unit.class);
            if(unit != null){
                if(unit.getCityCode().equals("65")){
                    roleList = roleService.findAll1();
                }else {
                    roleList = roleService.findAllByIsCity(1);
                }
            }
        }
        return roleList != null ? new ResultState(StateInfo.FIND_OK.getCode(),
                StateInfo.FIND_OK.getMsg(), roleList) : new ResultState(StateInfo.FIND_NULL.getCode(),
                StateInfo.FIND_NULL.getMsg());
    }

    @SystemLog(type = SystemLogEnum.QUERY_LOG,moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @GetMapping("/findById/{id}")
    @ApiOperation("根据ID查询角色信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "角色ID", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "header", name = "token", value = "token密匙", required = true, dataType = "string")
    })
    public ResultState findById(@PathVariable("id")Long id) {
        Role role = roleService.findById(id);
        return role != null ? new ResultState(StateInfo.FIND_OK.getCode(),
                StateInfo.FIND_OK.getMsg(), role) : new ResultState(StateInfo.FIND_NULL.getCode(),
                StateInfo.FIND_NULL.getMsg());
    }

    @SystemLog(type = SystemLogEnum.QUERY_LOG,moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @GetMapping("/findPages")
    @ApiOperation("分页查询角色信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "pageNumber", value = "当前页码", required = true, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页行数", required = true, dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "roleName", value = "角色名称", required = false, dataType = "string"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState findPagesByUserNameAndUnitId(Integer pageNumber, Integer pageSize, String roleName) throws IOException {
        //改为加密
        return roleService.findPageList(pageNumber, pageSize, roleName);
    }

    @SystemLog(type = SystemLogEnum.SAVE_LOG,moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @PostMapping("/save")
    @ApiOperation(value = "保存角色信息", notes = "保存角色信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "roleCode", value = "角色编码（例如：admin）", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "roleName", value = "角色名称（例如：管理员）", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "description", value = "角色描述", required = false, dataType = "string"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState save(@RequestBody Role role){
        return roleService.save(role);
    }

    @SystemLog(type = SystemLogEnum.UPDATE_LOG,moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @PostMapping("/update")
    @ApiOperation(value = "更新角色信息", notes = "更新角色信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "角色id", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "query", name = "roleCode", value = "角色编码（例如：admin）", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "roleName", value = "角色名称（例如：管理员）", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "description", value = "角色描述", required = false, dataType = "string"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState update(@RequestBody Role role){
        return roleService.update(role);
    }

    @SystemLog(type = SystemLogEnum.DELETE_LOG,moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除角色信息", notes = "删除角色信息(用户资源清单没有关联该角色方可删除)")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "资源清单ID", required = true, dataType = "long"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState delete(@PathVariable("id") Long id) throws IOException {
        //改为加密
        return roleService.delete(id);
    }

    @SystemLog(type = SystemLogEnum.DELETE_LOG,moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @DeleteMapping("/menu/deleteMenuRolesConnection/{roleId}/{menuId}")
    @ApiOperation(value = "删除角色下的关联资源", notes = "删除角色下的关联资源（删除父级时同时删除子级）")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "roleId", value = "角色ID", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "path", name = "menuId", value = "资源清单ID", required = true, dataType = "long"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState deleteMenuRolesConnection(@PathVariable("roleId") Long roleId,@PathVariable("menuId") Long menuId) throws IOException {
        //改为加密
        return roleService.deleteConnectionByMenuId(roleId, menuId);
    }

    /*********资源*********/

    @SystemLog(type = SystemLogEnum.UPDATE_LOG,moduleMessage = MenuSourceEnum.MENU_BACKSTAGE)
    @PostMapping("/menu/updateMenuRoles")
    @ApiOperation(value = "根据角色ID更新关联资源清单信息", notes = "根据角色ID更新关联资源清单信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "roleId", value = "角色ID", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "query", name = "menuIdList", value = "角色关联资源清单ID列表", required = true, dataType = "list"),

            @ApiImplicitParam(paramType = "header", name = "token", value = "token", required = true, dataType = "string")
    })
    public ResultState update(@RequestBody MenuRolesDto menuRolesDto) throws IOException {
        //改为加密
        return menuService.updateMenuRoles(menuRolesDto);
    }

    @GetMapping("/menu/findAllMenuDtos")
    @ApiOperation("查询所有资源清单树")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "token密匙", required = true, dataType = "string")
    })
    public ResultState findAllMenuDtos() {
        List<MenuDto> menuDtoList = menuService.findAllMenuDto();
        return menuDtoList != null ? new ResultState(StateInfo.FIND_OK.getCode(),
                StateInfo.FIND_OK.getMsg(), menuDtoList) : new ResultState(StateInfo.FIND_NULL.getCode(),
                StateInfo.FIND_NULL.getMsg());
    }

    @GetMapping("/menu/findAllByRoleId/{roleId}")
    @ApiOperation("根据角色ID查询资源清单树信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "roleId", value = "角色ID", required = true, dataType = "long"),
            @ApiImplicitParam(paramType = "header", name = "token", value = "token密匙", required = true, dataType = "string")
    })
    public ResultState findAllByRoleId(@PathVariable("roleId")Long roleId) throws IOException {
        //改为加密
        List<MenuDto> menuDtoList = menuService.findByRoleId(roleId);
        return menuDtoList != null ? new ResultState(StateInfo.FIND_OK.getCode(),
                StateInfo.FIND_OK.getMsg(), menuDtoList) : new ResultState(StateInfo.FIND_NULL.getCode(),
                StateInfo.FIND_NULL.getMsg());
    }
}
